import React, { useState, useEffect } from 'react';
import { Spin, Pagination } from 'antd';
import { ApiService } from '../services/api';
import './DownloadsPage.css';

const DownloadsPage = () => {
  const [downloads, setDownloads] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  const pageSize = 10;

  // 获取资料列表
  useEffect(() => {
    const fetchDownloads = async () => {
      try {
        setLoading(true);
        setError(null);
        
        const response = await ApiService.getDocumentListPage(currentPage, pageSize);
        
        if (response.code === '0000' && response.data) {
          // 转换API数据格式
          const formattedDownloads = response.data.map(item => ({
            id: item.fileId,
            title: item.fileName,
            description: '', // API没有返回描述，可以后续扩展
            type: item.fileType?.toUpperCase() || 'FILE',
            size: item.fileSize || '未知大小',
            icon: getFileIcon(item.fileType),
            fileUrl: item.fileUrl,
            updateTime: item.updateTime ? new Date(item.updateTime).toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit'
            }) : ''
          }));
          
          setDownloads(formattedDownloads);
          setTotal(response.total || 0);
        } else {
          setError('获取资料列表失败');
        }
      } catch (err) {
        console.error('获取资料列表失败:', err);
        setError('网络请求失败');
      } finally {
        setLoading(false);
      }
    };

    fetchDownloads();
  }, [currentPage]);

  // 根据文件类型获取图标
  const getFileIcon = (fileType) => {
    const type = fileType?.toLowerCase();
    switch (type) {
      case 'pdf':
        return '📄';
      case 'doc':
      case 'docx':
        return '📝';
      case 'xls':
      case 'xlsx':
        return '📊';
      case 'ppt':
      case 'pptx':
        return '📋';
      case 'zip':
      case 'rar':
        return '📦';
      case 'mp4':
      case 'avi':
        return '🎥';
      case 'jpg':
      case 'png':
      case 'gif':
        return '🖼️';
      default:
        return '📁';
    }
  };

  // 处理分页变化
  const handlePageChange = (page) => {
    setCurrentPage(page);
  };

  // 处理文件下载
  const handleDownload = (fileUrl, fileName) => {
    if (fileUrl) {
      // 创建一个临时的a标签来触发下载
      const link = document.createElement('a');
      link.href = fileUrl;
      link.download = fileName;
      link.target = '_blank';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } else {
      alert('文件链接不可用');
    }
  };

  if (loading) {
    return (
      <div className="downloads-page">
        <div className="container">
          <div className="page-header">
            <h1>资料下载</h1>
            <p>获取最新的产品资料、技术文档和开发工具</p>
          </div>
          <div className="loading-container">
            <Spin size="large" />
            <p>加载资料列表中...</p>
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="downloads-page">
        <div className="container">
          <div className="page-header">
            <h1>资料下载</h1>
            <p>获取最新的产品资料、技术文档和开发工具</p>
          </div>
          <div className="error-container">
            <p>{error}</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="downloads-page">
      <div className="container">
        <div className="page-header">
          <h1>资料下载</h1>
          <p>获取最新的产品资料、技术文档和开发工具</p>
        </div>

        <div className="downloads-list">
          {downloads.length > 0 ? (
            downloads.map(item => (
              <div key={item.id} className="download-item">
                <div className="download-icon">{item.icon}</div>
                <div className="download-content">
                  <div className="download-header">
                    <h3 className="download-title">{item.title}</h3>
                    <div className="download-meta">
                      <span className="download-type">{item.type}</span>
                    </div>
                  </div>
                  <div className="download-footer">
                    <div className="download-details">
                      <span className="download-size">{item.size}</span>
                      <span className="download-time">{item.updateTime}</span>
                    </div>
                    <button 
                      className="download-btn"
                      onClick={() => handleDownload(item.fileUrl, item.title)}
                    >
                      下载
                    </button>
                  </div>
                </div>
              </div>
            ))
          ) : (
            <div className="no-downloads">
              <p>暂无资料文件</p>
            </div>
          )}
        </div>

        {/* 分页组件 */}
        {total > 0 && (
          <div className="pagination-container">
            <Pagination
              current={currentPage}
              total={total}
              pageSize={pageSize}
              onChange={handlePageChange}
              showSizeChanger={false}
              showTotal={(total, range) => 
                `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
              }
            />
          </div>
        )}
      </div>
    </div>
  );
};

export default DownloadsPage;
